<template>
  <div class="connection-container">
    <div class="connection-form">
      <h2 class="form-title">连接设置</h2>
      
      <!-- 连接状态显示 -->
      <div v-if="connectionStatus" class="status-message" :class="connectionStatus.success ? 'success' : 'error'">
        {{ connectionStatus.message }}
      </div>
      
      <div class="form-group">
        <label class="form-label">
          Username<span class="required">*</span>
        </label>
        <input 
          type="text" 
          class="form-input" 
          v-model="formData.username" 
          placeholder="请输入用户名"
          :disabled="isConnecting"
        />
      </div>

      <div class="form-group">
        <label class="form-label">
          Password<span class="required">*</span>
        </label>
        <div class="password-input-container">
          <input 
            :type="showPassword ? 'text' : 'password'" 
            class="form-input password-input" 
            v-model="formData.password" 
            placeholder="请输入密码"
            :disabled="isConnecting"
          />
          <button 
            type="button" 
            class="password-toggle" 
            @click="togglePassword"
            :disabled="isConnecting"
          >
            <svg v-if="showPassword" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
              <circle cx="12" cy="12" r="3"/>
            </svg>
            <svg v-else width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/>
              <line x1="1" y1="1" x2="23" y2="23"/>
            </svg>
          </button>
        </div>
      </div>

      <div class="form-group">
        <label class="form-label">
          Domain<span class="required">*</span>
        </label>
        <input 
          type="text" 
          class="form-input" 
          v-model="formData.domain" 
          placeholder="请输入域名和端口"
          :disabled="isConnecting"
        />
      </div>

      <div class="form-group">
        <label class="form-label">
          Display name
        </label>
        <input 
          type="text" 
          class="form-input" 
          v-model="formData.displayName" 
          placeholder="请输入显示名称"
          :class="{ 'focused': focusedField === 'displayName' }"
          @focus="focusedField = 'displayName'"
          @blur="focusedField = ''"
          :disabled="isConnecting"
        />
      </div>

      <div class="form-group">
        <label class="form-label">
          Transport
        </label>
        <select class="form-input" v-model="formData.transport" :disabled="isConnecting">
          <option value="TCP">TCP</option>
          <option value="UDP">UDP</option>
          <option value="TLS">TLS</option>
        </select>
      </div>

      <button 
        type="button" 
        class="connection-button" 
        @click="handleConnection"
        :disabled="isConnecting"
        :class="{ 'connecting': isConnecting }"
      >
        <span v-if="isConnecting">连接中...</span>
        <span v-else-if="isConnected">断开连接</span>
        <span v-else>Connection</span>
      </button>
    </div>
  </div>
</template>

<script>
const { invoke } = window.__TAURI__.core;

export default {
  name: 'ConnectionForm',
  data() {
    return {
      showPassword: false,
      focusedField: '',
      isConnecting: false,
      isConnected: false,
      connectionStatus: null,
      formData: {
        username: '1002',
        password: '',
        domain: '192.168.43.252:5060',
        displayName: '',
        transport: 'TCP'
      }
    }
  },
  async mounted() {
    // 页面加载时检查连接状态
    await this.checkConnectionStatus();
  },
  methods: {
    togglePassword() {
      this.showPassword = !this.showPassword;
    },
    
    async handleConnection() {
      if (this.isConnected) {
        // 如果已连接，则断开连接
        await this.disconnectSip();
      } else {
        // 如果未连接，则建立连接
        await this.connectSip();
      }
    },
    
    async connectSip() {
      this.isConnecting = true;
      this.connectionStatus = null;
      
      try {
        // 验证表单数据
        if (!this.validateForm()) {
          return;
        }
        
        console.log('开始SIP连接:', this.formData);
        
        // 调用Tauri后端的SIP连接方法
        const result = await invoke('connect_sip', {
          config: {
            username: this.formData.username,
            password: this.formData.password,
            domain: this.formData.domain,
            display_name: this.formData.displayName || null,
            transport: this.formData.transport
          }
        });
        
        console.log('SIP连接结果:', result);
        
        if (result.success) {
          this.isConnected = true;
          this.connectionStatus = {
            success: true,
            message: result.message
          };
          // 连接成功后跳转到通话页面
          this.$router.push({ name: 'Calls' });
        } else {
          this.connectionStatus = {
            success: false,
            message: result.message || '连接失败'
          };
        }
      } catch (error) {
        console.error('SIP连接错误:', error);
        this.connectionStatus = {
          success: false,
          message: `连接失败: ${error}`
        };
      } finally {
        this.isConnecting = false;
      }
    },
    
    async disconnectSip() {
      this.isConnecting = true;
      
      try {
        console.log('断开SIP连接');
        
        const result = await invoke('disconnect_sip');
        
        console.log('断开连接结果:', result);
        
        if (result.success) {
          this.isConnected = false;
          this.connectionStatus = {
            success: true,
            message: result.message
          };
        } else {
          this.connectionStatus = {
            success: false,
            message: result.message || '断开连接失败'
          };
        }
      } catch (error) {
        console.error('断开连接错误:', error);
        this.connectionStatus = {
          success: false,
          message: `断开连接失败: ${error}`
        };
      } finally {
        this.isConnecting = false;
      }
    },
    
    async checkConnectionStatus() {
      try {
        const result = await invoke('get_connection_status');
        this.isConnected = result.success;
        if (result.success) {
          this.connectionStatus = {
            success: true,
            message: result.message
          };
        }
      } catch (error) {
        console.error('检查连接状态错误:', error);
      }
    },
    
    validateForm() {
      if (!this.formData.username.trim()) {
        this.connectionStatus = {
          success: false,
          message: '请输入用户名'
        };
        return false;
      }
      
      if (!this.formData.password.trim()) {
        this.connectionStatus = {
          success: false,
          message: '请输入密码'
        };
        return false;
      }
      
      if (!this.formData.domain.trim()) {
        this.connectionStatus = {
          success: false,
          message: '请输入域名和端口'
        };
        return false;
      }
      
      return true;
    }
  }
}
</script>

<style scoped>
.connection-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.connection-form {
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

.form-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.status-message {
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-size: 14px;
  font-weight: 500;
}

.status-message.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.status-message.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.required {
  color: #ff6b35;
  margin-left: 2px;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  background-color: #f8f9fa;
  color: #495057;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #ff6b35;
  background-color: white;
}

.form-input.focused {
  border-color: #ff6b35;
  background-color: white;
}

.form-input:disabled {
  background-color: #e9ecef;
  color: #6c757d;
  cursor: not-allowed;
}

.password-input-container {
  position: relative;
}

.password-input {
  padding-right: 50px;
}

.password-toggle {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  color: #6c757d;
  padding: 4px;
  border-radius: 4px;
  transition: color 0.3s ease;
}

.password-toggle:hover:not(:disabled) {
  color: #ff6b35;
}

.password-toggle:disabled {
  color: #adb5bd;
  cursor: not-allowed;
}

select.form-input {
  cursor: pointer;
  appearance: none;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
  background-position: right 12px center;
  background-repeat: no-repeat;
  background-size: 16px;
  padding-right: 40px;
}

select.form-input:disabled {
  cursor: not-allowed;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%23adb5bd' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
}

.connection-button {
  width: 100%;
  padding: 14px 20px;
  background-color: #ff6b35;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 10px;
}

.connection-button:hover:not(:disabled) {
  background-color: #e55a2b;
}

.connection-button:active:not(:disabled) {
  transform: translateY(1px);
}

.connection-button:disabled {
  background-color: #adb5bd;
  cursor: not-allowed;
  transform: none;
}

.connection-button.connecting {
  background-color: #6c757d;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .connection-form {
    padding: 30px 20px;
    margin: 10px;
  }
  
  .form-title {
    font-size: 20px;
  }
}
</style>
